<template>
  <div>
    <!-- 导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜素框区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable
            @clear="getUserList">
            <!-- 搜索框利用slot属性插入 -->
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加按钮</el-button>
        </el-col>
      </el-row>
      <el-row>
        <!-- 用户列表 -->
        <el-table :data="userList" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名">
          </el-table-column>
          <el-table-column prop="email" label="邮箱">
          </el-table-column>
          <el-table-column prop="mobile" label="电话">
          </el-table-column>
          <el-table-column prop="role_name" label="角色">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <!-- 作用域插槽 -->
            <template v-slot="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template v-slot="{row}">
              <!-- 编辑按钮 -->
              <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(row.id)">
              </el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" class="el-icon-delete" size="mini" @click="delUser(row.id)"></el-button>
              <!-- 分配角色 -->
              <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
                <el-button type="warning" class="el-icon-s-tools" size="mini" @click="setRoles(row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 添加弹出提示框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="resetaddForm">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username" class="is-required">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="is-required">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="is-required">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile" class="is-required">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出修改用户信息 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="reseteditForm">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="is-required">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" class="is-required">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="50%" @close="resetRights">
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="roleSelectId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNewRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 邮箱验证
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+([a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    };
    // 手机号码验证
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的电话号码'))
    };
    return {
      // 获取用户列表
      queryInfo: {
        pagenum: 1,
        pagesize: 5,
        query: ''
      },
      userList: [],
      total: 0,
      dialogVisible: false,  // 控制隐藏显示
      // 添加表单验证数据
      addForm: {
        username: "",
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { require: true, message: '请输入登录名', trigger: 'blur' },          // trigger自动触发为鼠标事件
          {
            min: 3,
            max: 10,
            message: '登录名长度为3到10个字符',
            trigger: 'blur'
          },
        ],
        password: [
          { require: true, message: '请输入密码', trigger: 'blur' },          // trigger自动触发为鼠标事件
          {
            min: 6,
            max: 15,
            message: '密码长度为6到15个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { require: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { require: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},   //  查询到用户信息
      // 验证查询表单规则
      editFormRules: {
        email: [
          { require: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { require: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setDialogVisible: false,
      rolesList: [],  //  角色数据列表
      userInfo: {},   // 需要分配用户角色
      roleSelectId: '', // 已选的角色ID
    }
  },
  methods: {
    resetRights () {
      this.roleSelectId = ''
    },
    // 新角色确定
    async saveNewRole () {
      if (!this.roleSelectId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,
        { rid: this.roleSelectId }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setDialogVisible = false
    },
    // 分配角色
    async setRoles (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
      this.setDialogVisible = true
    },
    async getUserList () {
      const { data: res } = await this.$http.get(
        'users',
        { params: this.queryInfo }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！');
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.queryInfo.query);
      // console.log(res);
    },
    resetaddForm () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) { return }
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    handleSizeChange (newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged (userInfo) {
      // console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听查询对话关闭重置
    reseteditForm () {
      this.$refs.editFormRef.resetFields()
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          mobile: this.editForm.mobile,
          email: this.editForm.email
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('修改用户信息成功')
      })
    },
    async delUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getUserList()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
